package com.hu.system.service.impl;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.hu.common.exception.ServiceException;
import com.hu.common.utils.SecurityUtils;
import com.hu.common.utils.StringUtils;
import com.hu.system.mapper.ProfitAftersaleMapper;
import com.hu.system.mapper.SysUserShopMapper;
import com.hu.system.domain.ProfitAftersale;
import com.hu.system.domain.ProductInfo;
import com.hu.system.service.IProfitAftersaleService;
import com.hu.system.service.IProductInfoService;

/**
 * 售后明细Service业务层处理
 *
 * @author hu
 * @date 2025-01-21
 */
@Service
public class ProfitAftersaleServiceImpl implements IProfitAftersaleService {
    @Autowired
    private ProfitAftersaleMapper profitAftersaleMapper;

    @Autowired
    private SysUserShopMapper userShopMapper;

    @Autowired
    private IProductInfoService productInfoService;

    /**
     * 查询售后明细列表
     *
     * @param profitAftersale 售后明细
     * @return 售后明细
     */
    @Override
    public List<ProfitAftersale> selectProfitAftersaleList(ProfitAftersale profitAftersale) {
        Long userId = SecurityUtils.getUserId();

        // 管理员查看全部
        if (userId != null && SecurityUtils.isAdmin(userId)) {
            return profitAftersaleMapper.selectProfitAftersaleList(profitAftersale);
        }

        // 普通用户根据店铺过滤
        // 保存分页参数（因为查询店铺ID会消耗分页上下文）
        Page<?> page = PageHelper.getLocalPage();
        PageHelper.clearPage();
        List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
        if (shopIds == null || shopIds.isEmpty()) {
            return new ArrayList<>();
        }
        // 恢复分页参数
        if (page != null) {
            PageHelper.startPage(page.getPageNum(), page.getPageSize(), page.getOrderBy());
        }

        // 设置店铺ID过滤条件
        profitAftersale.getParams().put("shopIdList", shopIds);

        return profitAftersaleMapper.selectProfitAftersaleList(profitAftersale);
    }

    /**
     * 查询售后明细
     *
     * @param aftersaleId 售后明细主键
     * @return 售后明细
     */
    @Override
    public ProfitAftersale selectProfitAftersaleByAftersaleId(Long aftersaleId) {
        ProfitAftersale profitAftersale = profitAftersaleMapper.selectProfitAftersaleByAftersaleId(aftersaleId);

        // 数据权限校验
        if (profitAftersale != null) {
            Long userId = SecurityUtils.getUserId();
            if (userId != null && !SecurityUtils.isAdmin(userId)) {
                PageHelper.clearPage();
                List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
                if (shopIds == null || !shopIds.contains(profitAftersale.getShopId())) {
                    return null;
                }
            }
        }

        return profitAftersale;
    }

    /**
     * 新增售后明细
     *
     * @param profitAftersale 售后明细
     * @return 结果
     */
    @Override
    @Transactional
    public int insertProfitAftersale(ProfitAftersale profitAftersale) {
        profitAftersale.setCreateBy(SecurityUtils.getUsername());
        profitAftersale.setDelFlag("0");
        return profitAftersaleMapper.insertProfitAftersale(profitAftersale);
    }

    /**
     * 修改售后明细
     *
     * @param profitAftersale 售后明细
     * @return 结果
     */
    @Override
    @Transactional
    public int updateProfitAftersale(ProfitAftersale profitAftersale) {
        // 数据权限校验
        ProfitAftersale existingAftersale = selectProfitAftersaleByAftersaleId(profitAftersale.getAftersaleId());
        if (existingAftersale == null) {
            return 0;
        }

        profitAftersale.setUpdateBy(SecurityUtils.getUsername());
        return profitAftersaleMapper.updateProfitAftersale(profitAftersale);
    }

    /**
     * 批量删除售后明细
     *
     * @param aftersaleIds 需要删除的售后明细主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteProfitAftersaleByAftersaleIds(Long[] aftersaleIds) {
        // 数据权限校验
        Long userId = SecurityUtils.getUserId();
        if (userId != null && !SecurityUtils.isAdmin(userId)) {
            PageHelper.clearPage();
            List<Long> shopIds = userShopMapper.selectShopIdsByUserId(userId);
            for (Long aftersaleId : aftersaleIds) {
                ProfitAftersale profitAftersale = profitAftersaleMapper.selectProfitAftersaleByAftersaleId(aftersaleId);
                if (profitAftersale == null || !shopIds.contains(profitAftersale.getShopId())) {
                    return 0;
                }
            }
        }

        return profitAftersaleMapper.deleteProfitAftersaleByAftersaleIds(aftersaleIds);
    }

    /**
     * 删除售后明细信息
     *
     * @param aftersaleId 售后明细主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteProfitAftersaleByAftersaleId(Long aftersaleId) {
        // 数据权限校验
        ProfitAftersale existingAftersale = selectProfitAftersaleByAftersaleId(aftersaleId);
        if (existingAftersale == null) {
            return 0;
        }

        return profitAftersaleMapper.deleteProfitAftersaleByAftersaleId(aftersaleId);
    }

    /**
     * 导入售后明细数据（自动识别并读取两个sheet）
     *
     * @param file          上传的Excel文件
     * @param updateSupport 是否更新支持
     * @param shopId        所属店铺ID
     * @return 导入结果消息
     */
    @Override
    @Transactional
    public String importProfitAftersale(MultipartFile file, boolean updateSupport, Long shopId) throws Exception {
        InputStream is = file.getInputStream();
        Workbook workbook = WorkbookFactory.create(is);

        int totalSuccessNum = 0;
        int totalFailureNum = 0;
        int totalCreatedProductCount = 0;
        int totalUpdatedProductCount = 0;
        StringBuilder resultMsg = new StringBuilder();

        // 定义需要读取的sheet名称和对应的售后金额列名
        String[] sheetConfigs = {
//                "结算-消费者退款金额|消费者退款金额",
                "消费者及履约保障-售后问题|赔付金额"
        };

        // 遍历两个sheet
        for (String config : sheetConfigs) {
            String[] parts = config.split("\\|");
            String sheetName = parts[0];
            String amountColumnName = parts[1];

            Sheet sheet = workbook.getSheet(sheetName);
            if (sheet == null) {
                continue; // 如果sheet不存在，跳过
            }

            // 处理该sheet的数据
            int[] result = processSheetData(sheet, sheetName, amountColumnName, shopId);

            totalSuccessNum += result[0];
            totalFailureNum += result[1];
            totalCreatedProductCount += result[2];
            totalUpdatedProductCount += result[3];

            resultMsg.append("<br/><br/>【").append(sheetName).append("】导入 ").append(result[0]).append(" 条成功");
            if (result[1] > 0) {
                resultMsg.append("，").append(result[1]).append(" 条失败");
            }
        }

        workbook.close();
        is.close();

        if (totalSuccessNum == 0 && totalFailureNum == 0) {
            throw new ServiceException("未找到有效的sheet页，请确保Excel中包含以下任一sheet页：1)结算-消费者退款金额 2)消费者及履约保障-售后问题");
        }

        StringBuilder finalMsg = new StringBuilder();
        finalMsg.append("导入完成！总计成功 " + totalSuccessNum + " 条");
        if (totalFailureNum > 0) {
            finalMsg.append("，失败 " + totalFailureNum + " 条");
        }

        // 添加产品操作统计
        if (totalCreatedProductCount > 0 || totalUpdatedProductCount > 0) {
            finalMsg.append("<br/><br/>【产品处理统计】");
            if (totalCreatedProductCount > 0) {
                finalMsg.append("<br/>新建产品：" + totalCreatedProductCount + " 个");
            }
            if (totalUpdatedProductCount > 0) {
                finalMsg.append("<br/>更新产品：" + totalUpdatedProductCount + " 个");
            }
        }

        finalMsg.append(resultMsg.toString());

        return finalMsg.toString();
    }

    /**
     * 处理单个sheet的数据
     */
    private int[] processSheetData(Sheet sheet, String sheetName, String amountColumnName, Long shopId) {
        int successNum = 0;
        int failureNum = 0;
        List<ProfitAftersale> batchInsertList = new ArrayList<>();
        // 生成导入备注，根据sheet名称调整
        String remarkPrefix = sheetName;
        if (sheetName.startsWith("结算-")) {
            remarkPrefix = sheetName.replace("结算-", "");
        }
        String importRemark = remarkPrefix + "【导入于 " + com.hu.common.utils.DateUtils.getTime() + "】";
        // 本批次已处理的SKU集合，避免重复插入product_info
        java.util.Set<String> processedSkus = new java.util.HashSet<>();

        // 记录产品操作统计
        int createdProductCount = 0;
        int updatedProductCount = 0;
        java.util.List<String> updatedProductDetails = new java.util.ArrayList<>();

        // 读取表头，找到金额列索引
        Row headerRow = sheet.getRow(0);
        if (headerRow == null) {
            return new int[]{0, 0};
        }

        int amountColumnIndex = -1;
        for (int i = 0; i < headerRow.getLastCellNum(); i++) {
            Cell cell = headerRow.getCell(i);
            if (cell != null && amountColumnName.equals(cell.getStringCellValue())) {
                amountColumnIndex = i;
                break;
            }
        }

        if (amountColumnIndex == -1) {
            return new int[]{0, 0}; // 找不到金额列
        }

        // 读取数据行
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;

            try {
                ProfitAftersale aftersale = new ProfitAftersale();

                // SKU ID
                Cell skuCell = row.getCell(getColumnIndex(headerRow, "SKU ID"));
                if (skuCell == null || StringUtils.isEmpty(getCellStringValue(skuCell))) {
                    failureNum++;
                    continue;
                }
                aftersale.setSku(getCellStringValue(skuCell));

                // 货品名称
                int nameColIndex = getColumnIndex(headerRow, "货品名称");
                if (nameColIndex != -1) {
                    Cell nameCell = row.getCell(nameColIndex);
                    if (nameCell != null) {
                        aftersale.setProductName(getCellStringValue(nameCell));
                    }
                }

                // SKU属性（可选列，某些sheet可能没有此列）
                int attrColIndex = getColumnIndex(headerRow, "SKU属性");
                if (attrColIndex != -1) {
                    Cell attrCell = row.getCell(attrColIndex);
                    if (attrCell != null) {
                        aftersale.setSkuAttr(getCellStringValue(attrCell));
                    }
                }

                // 售后金额（使用动态列索引）
                Cell amountCell = row.getCell(amountColumnIndex);
                if (amountCell != null) {
                    aftersale.setAftersaleAmount(getCellBigDecimalValue(amountCell));
                }

                // 账务时间
                int dateColIndex = getColumnIndex(headerRow, "账务时间");
                if (dateColIndex != -1) {
                    Cell dateCell = row.getCell(dateColIndex);
                    if (dateCell != null) {
                        aftersale.setArrivalDate(getCellDateValue(dateCell));
                    }
                }

                // 检查产品是否存在，不存在则自动创建，存在则更新
                // 同一批次中相同SKU只处理一次，避免唯一键冲突
                ProductInfo product = null;
                if (!processedSkus.contains(aftersale.getSku())) {
                    com.hu.system.domain.ProductOperationResult operationResult = productInfoService.getOrCreateProduct(
                            aftersale.getSku(),
                            aftersale.getProductName(),
                            aftersale.getSkuAttr(),
                            null,  // skuCode为空时服务层会自动设置为sku
                            shopId
                    );
                    product = operationResult.getProduct();
                    processedSkus.add(aftersale.getSku());

                    // 统计产品操作
                    if (operationResult.getOperationType() == com.hu.system.domain.ProductOperationResult.OperationType.CREATED) {
                        createdProductCount++;
                    } else if (operationResult.getOperationType() == com.hu.system.domain.ProductOperationResult.OperationType.UPDATED) {
                        updatedProductCount++;
                        updatedProductDetails.add("SKU[" + aftersale.getSku() + "]" + operationResult.getUpdateDescription());
                    }
                } else {
                    // 本批次已处理过该SKU，从数据库查询产品信息（按SKU和店铺ID查询）
                    product = productInfoService.selectProductInfoBySkuAndShopId(aftersale.getSku(), shopId);
                }

                // 设置店铺ID
                aftersale.setShopId(shopId);

                // 从产品信息中补充字段
                if (product != null) {
                    if (StringUtils.isEmpty(aftersale.getProductName())) {
                        aftersale.setProductName(product.getProductName());
                    }
                    if (StringUtils.isEmpty(aftersale.getSkuAttr())) {
                        aftersale.setSkuAttr(product.getSkuAttr());
                    }
                }

                // 添加导入备注标识
                if (StringUtils.isEmpty(aftersale.getRemark())) {
                    aftersale.setRemark(importRemark);
                } else {
                    aftersale.setRemark(aftersale.getRemark() + " " + importRemark);
                }

                // 设置基础字段
                aftersale.setDelFlag("0");
                aftersale.setCreateBy(SecurityUtils.getUsername());

                // 添加到批量插入列表
                batchInsertList.add(aftersale);
                successNum++;

            } catch (Exception e) {
                failureNum++;
            }
        }

        // 批量插入（每500条一批）
        if (!batchInsertList.isEmpty()) {
            int batchSize = 500;
            for (int i = 0; i < batchInsertList.size(); i += batchSize) {
                int endIndex = Math.min(i + batchSize, batchInsertList.size());
                List<ProfitAftersale> subList = batchInsertList.subList(i, endIndex);
                profitAftersaleMapper.batchInsertProfitAftersale(subList);
            }
        }

        // 返回：[0]成功数 [1]失败数 [2]新建产品数 [3]更新产品数
        return new int[]{successNum, failureNum, createdProductCount, updatedProductCount};
    }

    /**
     * 根据列名获取列索引
     */
    private int getColumnIndex(Row headerRow, String columnName) {
        for (int i = 0; i < headerRow.getLastCellNum(); i++) {
            Cell cell = headerRow.getCell(i);
            if (cell != null && columnName.equals(cell.getStringCellValue())) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 获取单元格字符串值
     */
    private String getCellStringValue(Cell cell) {
        if (cell == null) return null;
        if (cell.getCellType() == CellType.STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellType() == CellType.NUMERIC) {
            return String.valueOf((long) cell.getNumericCellValue());
        }
        return null;
    }

    /**
     * 获取单元格BigDecimal值
     */
    private BigDecimal getCellBigDecimalValue(Cell cell) {
        if (cell == null) return null;
        if (cell.getCellType() == CellType.NUMERIC) {
            return BigDecimal.valueOf(cell.getNumericCellValue());
        } else if (cell.getCellType() == CellType.STRING) {
            try {
                return new BigDecimal(cell.getStringCellValue());
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 获取单元格日期值
     */
    private java.util.Date getCellDateValue(Cell cell) {
        if (cell == null) return null;

        try {
            // 1. 如果是数值类型且是日期格式
            if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
                return cell.getDateCellValue();
            }

            // 2. 如果是文本类型，尝试解析日期字符串
            if (cell.getCellType() == CellType.STRING) {
                String dateStr = cell.getStringCellValue();
                if (StringUtils.isNotEmpty(dateStr)) {
                    // 尝试多种日期格式解析
                    return com.hu.common.utils.DateUtils.parseDate(dateStr);
                }
            }
        } catch (Exception e) {
            // 日期解析失败，返回null
        }

        return null;
    }
}

